<?php
namespace EmailDelivery\Templates\Recovery;

use Users\Profile;
use Pinenut\User\Auth\EmailPassword;

/**
 * Created by ITokarev
 *
 * Recover Email Delivery Template
 */
class TemplateAction extends \Action {

	protected static $layout = '#emailDelivery.templates.layout';

	public function run( ) {
		$userMail = $this->request->email;
		
		if (! $userMail) {
			throw new \Exception('Email not Found', 500);
		}
		
		$auth = EmailPassword::find()
			->where('email', $userMail)
			->active()
			->one();
		
		if (! $auth) {
// для модератора из-под социалки, для которого не нашли аккаунт
//			$this->response->noRender(true);
//			return;
			throw new \Exception('Auth not Found', 500);
		}
		
		$code = $this->request->code;
		
		if (! $code) {
			$code = EmailPassword::generateRecoveryCode($userMail);
		}
		
		$this->response->code = $code;
		$profile = $auth->profile->getEntity();
		
		$this->response->userName = $profile->nickname;
		$this->response->profile = $profile;
		
		$this->response->set('title', 'Recovery Code');
		$this->response->set('to', $auth->email);
		
		$this->response->email = $auth->email;
	}
}